<?php

namespace App\Http\Middleware;

use App\Exceptions\TokenException;
use Closure;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\Facades\JWTAuth;

class CheckAuthorization
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next,$role=null)
    {
        if($role){
            auth()->shouldUse($role);
            $token=$request->header('Authorization');
            if(config('app.debug') && is_numeric($token)){
                auth()->setToken(auth()->tokenById($token));
                return $next($request);
            }
            $token_role = JWTAuth::parseToken()->getClaim('role');
            if ($token_role && $token_role == $role) {
                return $next($request);
            }
        }

        throw  new TokenException();
    }
}
